//var fs = require('fs-extra'); //旧的复制方法

var path = require('path');

var glob = require('glob');

var webpack = require('webpack');

var ExtractTextPlugin = require("extract-text-webpack-plugin");

var CommonsChunkPlugin = require("webpack/lib/optimize/CommonsChunkPlugin");

var HtmlWebpackPlugin = require('html-webpack-plugin');

var TransferWebpackPlugin = require('transfer-webpack-plugin');

var CopyWebpackPlugin = require('copy-webpack-plugin');

// CSS浏览器前缀问题 自动加 -webkit -ms
/*var autoprefixer = require('autoprefixer');
 var precss = require('precss');*/

// 多入口文件
function getEntrys() {

  var entrys = {};

  var src = new RegExp(__dirname.replace(/\\/g, "/") + "/src/");

  entrys['front/js/index'] = __dirname + '/src/front/js/index.js';

  //三方库
  entrys['front/js/vendor'] = [
    //__dirname.replace(/\\/g, "/") + '/src/admin/libs/jquery/jquery.js',
    __dirname.replace(/\\/g, "/") + '/node_modules/vue/dist/vue.min.js',
    //__dirname.replace(/\\/g, "/") + '/src/admin/libs/lodash/lodash.js',
  ];


  return entrys;
};

module.exports = {
  context: __dirname + '/src',
  entry: getEntrys(),
  output: {
    path: path.resolve(__dirname, './dist'),
    publicPath: '', // '/dist/'
    filename: '[name].js'
  },
  resolve: {
    //查找module的话从这里开始查找
    modules: [
      path.join(__dirname, 'src'),
      "node_modules"
    ],
    //自动扩展文件后缀名，意味着我们require模块可以省略不写后缀名
    extensions: ['.js', '.json', '.less', '.vue'],
    //模块别名定义，方便后续直接引用别名，无须多写长长的地址
    alias: {'vue': 'vue/dist/vue'}
  },
  module: {
    /*test: /\.(js|jsx)$/,           //注意是正则表达式，不要加引号，匹配要处理的文件
     loader: 'eslint-loader',       //要使用的loader，"-loader"可以省略
     include: [path.resolve(__dirname, "src/app")],   //把要处理的目录包括进来
     exclude: [nodeModulesPath]     //排除不处理的目录*/
    rules: [
      {
        test: /\.vue$/,
        loader: 'vue-loader'
      },
      {
        test: /\.js$/,
        loader: 'babel-loader',
        exclude: /(node_modules|bower_components)/
      },
        {
            test: /\.(png|jpg|gif)$/,
            use: [
                {
                    loader: 'url-loader',
                    options: {
                        limit: 8192,
                        // CSS图片目录
                        name: '[path][name].[ext]'
                    }
                }
            ]
        },
        {
            test: /\.mp3$/,
            use: [
                {
                    loader: 'file-loader',
                    options: {
                        name: '[path][name].[ext]'
                    }
                }
            ]
        },
      {
        test: /\.less$/,
        //loader : 'css-loader',
        loader: ExtractTextPlugin.extract({
          fallback: 'style-loader',
          use: ['css-loader', 'less-loader']
        })
      },
      {
        test: /\.css$/,
        //use: ['style-loader','css-loader'],
        loader: ExtractTextPlugin.extract({
          fallback: 'style-loader',
          use: 'css-loader'
        })
      },
      {// bootstrap font-awesome
        test: /\.(woff|woff2)(\?v=\d+\.\d+\.\d+)?$/,
        loader: 'url-loader',
        query: {
          limit: 100,
          mimetype: 'application/font-woff',
          // 字体文件放置目录
          name: '[path][name].[ext]'
        }
      },
      {// bootstrap
        test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/,
        loader: 'url-loader',
        query: {
          limit: 100,
          mimetype: 'application/octet-stream',
          // 字体文件放置目录
          name: '[path][name].[ext]'
        }
      },
      {// bootstrap
        test: /\.eot(\?v=\d+\.\d+\.\d+)?$/,
        loader: 'file-loader',
        query: {
          limit: 100,
          // 字体文件放置目录
          name: '[path][name].[ext]'
        }
      },
      {// bootstrap
        test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
        loader: 'url-loader',
        query: {
          limit: 100,
          mimetype: 'application/image/svg+xml',
          // 字体文件放置目录
          name: '[path][name].[ext]'
        }
      },
      {// font-awesome
        test: /\.(otf|ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
        loader: "file-loader",
        query: {
          limit: 100,
          // 字体文件放置目录
          name: '[path][name].[ext]'
        }
      }
    ]
  },
  plugins: [
    // 全局依赖jQuery Vue
    new webpack.ProvidePlugin({
      /*$: "admin/libs/jquery/jquery",
      jQuery: "admin/libs/jquery/jquery",
      "window.jQuery": "admin/libs/jquery/jquery",
      _: "admin/libs/lodash/lodash",*/
      Vue: __dirname.replace(/\\/g, "/") + '/node_modules/vue/dist/vue.min.js'
    }),
    // 提取三方库
    //new webpack.optimize.CommonsChunkPlugin('vendor', 'vendor.js', Infinity),
    /*new CommonsChunkPlugin({
     name: "admin/common",
     chunks:['admin/js/index'],
     minChunks: Infinity
     }),
     new CommonsChunkPlugin({
     name: "front/common",
     chunks:['front/js/index'],
     minChunks: Infinity
     }),*/
    // 提取CSS文件
    new ExtractTextPlugin({
      filename: "[name].css"
    }),
    // 查找相等或近似的模块，避免在最终生成的文件中出现重复的模块
    //new webpack.optimize.DedupePlugin(),
    new webpack.HotModuleReplacementPlugin(),
    //前端模版替换资源路径(开发和生产环境路径不一样)
    new HtmlWebpackPlugin({
     template: 'front/views/index.html',
     filename: 'front/views/index.html',
     inject: 'body',
     chunks: ['front/js/vendor', 'front/js/index']
     }),
    new CopyWebpackPlugin([
      {
        from: './php',
        to: './php'
      },
      {
        from: './config.php',
        to: './config.php'
      },
      {
        from: './index.php',
        to: './index.php'
      },
      {
        from: './front/img',
        to: './front/img'
      },
      {
        from: './front/sound',
        to: './front/sound'
      },
      {
        from: './front/libs/js/create.min.js',
        to: './front/libs/js/create.min.js'
      },
      {
        from: './front/libs/js/WXJSSDK.js',
        to: './front/libs/js/WXJSSDK.js'
      }
    ])
    //把指定文件夹下的文件复制到指定的目录
    /*new TransferWebpackPlugin([
     {from: 'api',to: 'api'}
     ], path.resolve(__dirname,"src")),*/
    /*new webpack.DefinePlugin({
     'process.env': {
     NODE_ENV: 'production'
     }
     }),*/
    /*new webpack.optimize.UglifyJsPlugin({
     //sourceMap: true,
     compress: {
     warnings: false
     }
     })*/
  ],
  /*postcss : function() {
   return [ autoprefixer({
   browsers : [ 'not ie <= 8' ]
   }), precss ];
   },*/

  //devtool : 'eval-source-map'
  //devtool : 'cheap-module-source-map'
};


if (process.env.NODE_ENV === 'production') {
  //module.exports.devtool = 'source-map';
  // http://vuejs.github.io/vue-loader/workflow/production.html
  module.exports.plugins = (module.exports.plugins || []).concat([
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false
      },
    })
  ]);
  //旧的复制方法
  /*fs.copy(__dirname + '/src/config.php', __dirname + '/dist/config.php', err => {});
  fs.copy(__dirname + '/src/index.php', __dirname + '/dist/index.php', err => {});
  //fs.copy(__dirname + '/src/front/img', __dirname + '/dist/front/img', err => {});
  fs.copy(__dirname + '/src/front/sound', __dirname + '/dist/front/sound', err => {});
  fs.copy(__dirname + '/src/front/libs/js/create.min.js', __dirname + '/dist/front/libs/js/create.min.js', err => {});
  fs.copy(__dirname + '/src/front/libs/js/WXJSSDK.js', __dirname + '/dist/front/libs/js/WXJSSDK.js', err => {});*/
} else {
  module.exports.devtool = 'eval-source-map';
  // http://vuejs.github.io/vue-loader/workflow/production.html
  module.exports.plugins = (module.exports.plugins || []).concat([]);
  //Server Configuration options
  module.exports.devServer = {
    contentBase: path.join(__dirname, 'src'),  //静态资源的目录 相对路径,相对于当前路径 默认为当前config所在的目录
    hot: true,        //自动刷新
    inline: false,
    host: '192.168.1.103',
    port: 8848,
    headers: {
        "Access-Control-Allow-Origin": "*"
    }
  };
}